package com.yuelao.yuelao_backend.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yuelao.yuelao_backend.common.ApiResponse;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.util.JwtUtil;
import com.yuelao.yuelao_backend.entity.User;
import com.yuelao.yuelao_backend.service.security.CustomUserDetails;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request,
                                    @NonNull HttpServletResponse response,
                                    @NonNull FilterChain filterChain)
            throws ServletException, IOException {

        final String authHeader = request.getHeader("Authorization");
        
        // 如果没有Authorization头或格式不正确，继续过滤链（由Spring Security决定是否允许访问）
        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        try {
            final String jwt = authHeader.substring(7);

            if (SecurityContextHolder.getContext().getAuthentication() == null && jwtUtil.isTokenValid(jwt)) {
                String phone = jwtUtil.extractPhoneClaim(jwt);
                if (!StringUtils.hasText(phone)) {
                    phone = jwtUtil.extractUsername(jwt);
                }
                Long userId = jwtUtil.extractUserId(jwt);
                String nickname = jwtUtil.extractNickname(jwt);
                Integer status = jwtUtil.extractStatus(jwt);
                List<String> roles = jwtUtil.extractRoles(jwt);

                User user = new User();
                user.setId(userId);
                user.setPhone(phone);
                user.setNickname(nickname);
                user.setStatus(status);

                List<SimpleGrantedAuthority> authorities = roles.stream()
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());
                if (authorities.isEmpty()) {
                    authorities = java.util.Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
                }

                UserDetails userDetails = new CustomUserDetails(user, authorities);
                UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                        userDetails,
                        null,
                        userDetails.getAuthorities()
                );
                
                SecurityContextHolder.getContext().setAuthentication(authToken);
                filterChain.doFilter(request, response);
            }else {
                // JWT过期异常，返回统一的错误响应
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json;charset=UTF-8");

                ApiResponse<Object> apiResponse = ApiResponse.error(ErrorCode.TOKEN_EXPIRED_ERROR);
                ObjectMapper objectMapper = new ObjectMapper();
                response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
            }
        } catch (Exception e) {
            // 捕获其他JWT相关异常（如签名错误、格式错误等）
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setContentType("application/json;charset=UTF-8");
            
            ApiResponse<Object> apiResponse = ApiResponse.error(ErrorCode.NOT_LOGIN_ERROR, "Token无效");
            ObjectMapper objectMapper = new ObjectMapper();
            response.getWriter().write(objectMapper.writeValueAsString(apiResponse));
        }
    }
}